﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using YArchitech.Revit.RevitExtension;

namespace YJKArch.LeadToLeader
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	[Journaling(JournalingMode.NoCommandData)]
	public class LeadToLeader : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (LeadToLeader._hWndRevit == null)
			{
				Process[] processesByName = Process.GetProcessesByName("Revit");
				if (processesByName.Length != 0)
				{
					LeadToLeader._hWndRevit = new WindowHandle(processesByName[0].MainWindowHandle);
				}
			}
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Autodesk.Revit.DB.Document document = activeUIDocument.Document;
			Autodesk.Revit.DB.View activeView = document.ActiveView;
			XYZ xyz = null;
			XYZ xyz2 = null;
			XYZ xyz3 = null;
			Line line = null;
			ModelCurve modelCurve = null;
			XYZ coord = null;
			IListDate.FontFamily = Helper.GetSystemFamilyElementList<TextNoteType>(document);
			IEnumerable<Element> enumerable = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.ElementType)).ToElements();
			List<string> list = new List<string>();
			foreach (Element element in enumerable)
			{
				Autodesk.Revit.DB.ElementType elementType = (Autodesk.Revit.DB.ElementType)element;
				if (elementType.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME).AsString() == "箭头")
				{
					list.Add(elementType.Name);
				}
			}
			IListDate.ArrowType = list;
			LeadToLeaderForm leadToLeaderForm = new LeadToLeaderForm();
			leadToLeaderForm.Show(LeadToLeader._hWndRevit);
			int wMsg = 7;
			LeadToLeader.SendMessage(LeadToLeader._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			Result result;
			for (;;)
			{
				IL_11A:
				Transaction transaction = new Transaction(document);
				Transaction transaction2 = new Transaction(document);
				transaction.Start("revit");
				double num = 0.0;
				try
				{
					xyz = activeUIDocument.Selection.PickPoint("请选择一个点");
					leadToLeaderForm.Enabled = false;
					xyz2 = activeUIDocument.Selection.PickPoint("请选择第二个点");
					line = YJKLineEx.YJKGetBound(xyz, xyz2);
					XYZ xyz4 = xyz2 - xyz;
					if (leadToLeaderForm.ckbFixAngle)
					{
						double num2 = xyz4.AngleTo(new XYZ(1.0, 0.0, 0.0));
						XYZ xyz5 = null;
						double num3 = 0.0;
						try
						{
							num3 = double.Parse(leadToLeaderForm.ckbfixAngleSelect);
						}
						catch (Exception)
						{
						}
						if (xyz4.X >= 0.0 && xyz4.Y >= 0.0)
						{
							xyz5 = Helper.Rotate(xyz4, new XYZ(0.0, 0.0, 1.0), -(num2 - num3 * Math.PI / 180.0));
						}
						else if (xyz4.X <= 0.0 && xyz4.Y <= 0.0)
						{
							xyz5 = Helper.Rotate(xyz4, new XYZ(0.0, 0.0, 1.0), num2 + num3 * Math.PI / 180.0 + Math.PI);
						}
						else if (xyz4.X >= 0.0 && xyz4.Y <= 0.0)
						{
							xyz5 = Helper.Rotate(xyz4, new XYZ(0.0, 0.0, 1.0), num2 - num3 * Math.PI / 180.0);
						}
						else if (xyz4.X <= 0.0 && xyz4.Y >= 0.0)
						{
							xyz5 = Helper.Rotate(xyz4, new XYZ(0.0, 0.0, 1.0), -(num2 + num3 * Math.PI / 180.0 + Math.PI));
						}
						xyz2 = xyz + xyz5.Normalize() * line.Length;
					}
					Line line2 = YJKLineEx.YJKGetBound(xyz, xyz2);
					Plane plane = RevitVersionFuncs.CreatePlanByNormalAndOrigin(xyz2.CrossProduct(xyz), xyz);
					SketchPlane sketchPlane = RevitVersionFuncs.NewSketchPlane(document, plane);
					modelCurve = document.Create.NewModelCurve(line2, sketchPlane);
					transaction.Commit();
				}
				catch (Exception)
				{
					transaction.RollBack();
					if (leadToLeaderForm.Enabled)
					{
						leadToLeaderForm.Close();
						result = Autodesk.Revit.UI.Result.Succeeded;
						break;
					}
					leadToLeaderForm.Enabled = true;
					continue;
				}
				try
				{
					transaction2.Start("thridpoint");
					xyz3 = activeUIDocument.Selection.PickPoint("请选择第三个点");
					num = xyz2.X - xyz3.X;
					if (num < 0.0)
					{
						coord = new XYZ(xyz3.X, xyz2.Y + 0.8 * (double)activeView.Scale / 100.0, xyz2.Z);
					}
					else
					{
						coord = new XYZ(xyz3.X, xyz2.Y + 0.8 * (double)activeView.Scale / 100.0, xyz2.Z);
					}
				}
				catch (Exception)
				{
					transaction2.RollBack();
					if (leadToLeaderForm.Enabled)
					{
						leadToLeaderForm.Close();
					}
					else
					{
						leadToLeaderForm.Enabled = true;
					}
				}
				Element selectType = Helper.GetSelectType<Autodesk.Revit.DB.ElementType>(document, leadToLeaderForm.arrowType);
				XYZ baseVec = null;
				XYZ upVec = null;
				TextNote textNote = null;
				if (xyz2 != null)
				{
					new XYZ(xyz2.X, xyz2.Y, xyz2.Z);
					baseVec = new XYZ(1.0, 0.0, 0.0);
					upVec = new XYZ(0.0, 0.0, 1.0);
				}
				try
				{
                    textNote = document.GetTextNode(document.ActiveView, xyz2, baseVec, upVec, 1.0, (TextAlignFlags)64, (TextNoteLeaderTypes)0, (TextNoteLeaderStyles)1, xyz, xyz2, ".");
				}
				catch (Exception)
				{
				}
				XYZ xyz6 = null;
				if (leadToLeaderForm.alignStyle == "末端对齐")
				{
					xyz6 = xyz3;
				}
				else if (leadToLeaderForm.alignStyle == "居中对齐")
				{
					xyz6 = (xyz3 + xyz2) / 2.0;
				}
				else if (leadToLeaderForm.alignStyle == "始端对齐")
				{
					xyz6 = xyz2;
				}
				Element selectType2 = Helper.GetSelectType<TextNoteType>(document, leadToLeaderForm.fontType);
				XYZ origin = null;
				XYZ origin2 = null;
				byte[] array = null;
				byte[] array2 = null;
				if (leadToLeaderForm.LineUpText != null && leadToLeaderForm.LineUpText.Length > 0)
				{
					array = Encoding.Default.GetBytes(leadToLeaderForm.LineUpmaxLenth);
				}
				double num4 = Helper.FontSize(selectType2 as TextNoteType) * (double)activeView.Scale / 100.0;
				double num5 = selectType2.get_Parameter(BuiltInParameter.TEXT_SIZE).AsDouble() * (double)activeView.Scale;
				if (leadToLeaderForm.LineDownText != null && leadToLeaderForm.LineDownText.Length > 0)
				{
					array2 = Encoding.Default.GetBytes(leadToLeaderForm.LineDownmaxLent);
				}
				double num6 = 0.0;
				double num7 = 0.0;
				if (array != null && array.Length != 0)
				{
					num6 = (double)array.Length;
				}
				if (array2 != null && array2.Length != 0)
				{
					num7 = (double)array2.Length;
				}
				double num8 = 0.3 * (double)activeView.Scale / 100.0 * (double)leadToLeaderForm.lineUpRows;
				if (xyz6 != null)
				{
					if (num < 0.0)
					{
						if (leadToLeaderForm.alignStyle == "末端对齐")
						{
							origin = new XYZ(xyz6.X - num6 * num4 / 1.7 - num4 / 6.0 * (double)activeView.Scale / 100.0, xyz2.Y + num5 * (double)leadToLeaderForm.lineUpRows + num8, xyz6.Z);
							origin2 = new XYZ(xyz6.X - num7 * num4 / 1.7 - num4 / 6.0 * (double)activeView.Scale / 100.0, xyz2.Y, xyz6.Z);
						}
						else if (leadToLeaderForm.alignStyle == "居中对齐")
						{
							origin = new XYZ(xyz6.X - num6 * num4 / 1.7 / 2.0, xyz2.Y + num5 * (double)leadToLeaderForm.lineUpRows + num8, xyz6.Z);
							origin2 = new XYZ(xyz6.X - num7 * num4 / 1.7 / 2.0, xyz2.Y, xyz6.Z);
						}
						else if (leadToLeaderForm.alignStyle == "始端对齐")
						{
							origin = new XYZ(xyz6.X, xyz2.Y + num5 * (double)leadToLeaderForm.lineUpRows + num8, xyz6.Z);
							origin2 = new XYZ(xyz6.X, xyz2.Y, xyz6.Z);
						}
					}
					else if (leadToLeaderForm.alignStyle == "末端对齐")
					{
						origin = new XYZ(xyz6.X + num4 / 6.0 * (double)activeView.Scale / 100.0, xyz2.Y + num5 * (double)leadToLeaderForm.lineUpRows + num8, xyz6.Z);
						origin2 = new XYZ(xyz6.X + num4 / 6.0 * (double)activeView.Scale / 100.0, xyz2.Y, xyz6.Z);
					}
					else if (leadToLeaderForm.alignStyle == "居中对齐")
					{
						origin = new XYZ(xyz6.X - num6 * num4 / 1.7 / 2.0, xyz2.Y + num5 * (double)leadToLeaderForm.lineUpRows + num8, xyz6.Z);
						origin2 = new XYZ(xyz6.X - num7 * num4 / 1.7 / 2.0, xyz2.Y, xyz6.Z);
					}
					else if (leadToLeaderForm.alignStyle == "始端对齐")
					{
						origin = new XYZ(xyz6.X - num6 * num4 / 1.7, xyz2.Y + num5 * (double)leadToLeaderForm.lineUpRows + num8, xyz6.Z);
						origin2 = new XYZ(xyz6.X - num7 * num4 / 1.7, xyz2.Y, xyz6.Z);
					}
				}
				if (leadToLeaderForm.LineUpText != null && leadToLeaderForm.LineUpText.Length > 0)
				{
                    TextNote textNode = document.GetTextNode(document.ActiveView, origin, baseVec, upVec, 0.0001, (TextAlignFlags)64, leadToLeaderForm.LineUpText);
					textNode.TextNoteType = (selectType2 as TextNoteType);
					textNode.Width = (double)array.Length * num4;
				}
				if (leadToLeaderForm.LineUpText != null && leadToLeaderForm.LineDownText.Length > 0)
				{
                    TextNote textNode2 = document.GetTextNode(document.ActiveView, origin2, baseVec, upVec, 0.0001, (TextAlignFlags)64, leadToLeaderForm.LineDownText);
					textNode2.TextNoteType = (selectType2 as TextNoteType);
					textNode2.Width = (double)array2.Length * num4;
				}
				if (xyz3 != null)
				{
					try
					{
						textNote.Coord = coord;
						textNote.Width = 0.0;
						textNote.TextNoteType.get_Parameter(BuiltInParameter.LEADER_ARROWHEAD).Set(selectType.Id);
						textNote.HyGetLeaders().get_Item(0).Elbow = xyz2;
						document.Delete(modelCurve.Id);
						transaction2.Commit();
						goto IL_BB5;
					}
					catch (Exception)
					{
						transaction2.RollBack();
						result = Autodesk.Revit.UI.Result.Succeeded;
						break;
					}
					goto IL_BA3;
				}
				goto IL_BA3;
				IL_BB5:
				int num9 = 1;
				if (leadToLeaderForm.isCheckedShareLeader && xyz2 != null && xyz3 != null)
				{
					for (;;)
					{
						Transaction transaction3 = new Transaction(document);
						transaction3.Start("revits");
						XYZ end = null;
						try
						{
							end = activeUIDocument.Selection.PickPoint("请选择一个点");
						}
						catch (Exception)
						{
							if (!leadToLeaderForm.Enabled)
							{
								leadToLeaderForm.Enabled = true;
								transaction3.RollBack();
							}
							goto IL_11A;
						}
						if (textNote != null)
						{
							textNote.AddLeader(0);
							textNote.HyGetLeaders().get_Item(num9).End = end;
							textNote.HyGetLeaders().get_Item(num9).Elbow = xyz2;
							num9++;
							transaction3.Commit();
						}
					}
				}
				else
				{
					if (!leadToLeaderForm.isMorePointShareLine || xyz2 == null || xyz3 == null)
					{
						continue;
					}
					for (;;)
					{
						Transaction transaction4 = new Transaction(document);
						transaction4.Start("rvt");
						Line line3 = YJKLineEx.YJKGetBound(xyz, xyz2);
						line3.MakeUnbound();
						XYZ xyz7 = null;
						try
						{
							xyz7 = activeUIDocument.Selection.PickPoint("请选择一个点");
						}
						catch (Exception)
						{
							if (!leadToLeaderForm.Enabled)
							{
								leadToLeaderForm.Enabled = true;
								transaction4.RollBack();
								goto IL_11A;
							}
						}
						XYZ xyzpoint = line3.Project(xyz7).XYZPoint;
						textNote.AddLeader(0);
						textNote.HyGetLeaders().get_Item(num9).End = xyzpoint;
						num9++;
						transaction4.Commit();
					}
				}
				IL_BA3:
                if ((int)transaction2.GetStatus() == 1)
				{
					transaction2.RollBack();
					goto IL_BB5;
				}
				goto IL_BB5;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;
	}
}
